<!--
 * @description 宝石计算页面
 * @function 提供宝石等级与游戏币计算功能
 * @workflow 选择宝石类型 -> 输入等级和单价 -> 实时计算所需宝石数量和总费用
 * @author 开发团队
 * @date 2024-01-01
-->
<template>
	<div class='gemstone-container'>
		<!-- 宝石类型选择区域 -->
		<div class="gemstone-section gemstone-type-section">
			<div class="gemstone-tab-list">
				<div v-for="gem in gemTypes" :key="gem.id"
					:class="['gemstone-tab-item', { 'gemstone-tab-active': selectedGemType === gem.id }]"
					@click="handleGemTypeSelect(gem.id)">
					<div class="gemstone-tab-name">{{ gem.name }}</div>
				</div>
			</div>
		</div>

		<!-- 输入参数区域 -->
		<div class="gemstone-section gemstone-input-section">
			<div class="gemstone-input-group">
				<div class="gemstone-input-item">
					<div class="gemstone-input-label">目标宝石等级</div>
					<div class="gemstone-level-buttons">
						<div v-for="level in getLevelRange()" :key="level"
							:class="['gemstone-level-btn', { 'gemstone-level-btn-active': selectedLevel === level }]"
							@click="handleLevelSelect(level)">
							<div class="gemstone-level-btn-text">{{ level }}</div>
						</div>
					</div>
				</div>
				<div class="gemstone-input-item">
					<div class="gemstone-input-label">一级宝石单价[输入价格0-1000万之间]</div>
					<div class="gemstone-input-wrapper">
						<input type="number" v-model="basePrice" placeholder="请输入单价" class="gemstone-input-field"
							@input="handlePriceInput" @blur="handlePriceBlur" />
						<div class="gemstone-price-hint" v-if="basePrice">{{ getPriceHint() }}</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 计算结果区域 -->
		<div class="gemstone-section gemstone-result-section">
			<div class="gemstone-section-title">计算结果</div>
			<div class="gemstone-result-list">
				<div class="gemstone-result-item">
					<div class="gemstone-result-label">宝石类型</div>
					<div class="gemstone-result-value">{{ getGemTypeInfo() }}</div>
				</div>
				<div class="gemstone-result-item">
					<div class="gemstone-result-label">最高等级</div>
					<div class="gemstone-result-value">{{ getMaxLevel() }} 级</div>
				</div>
				<div class="gemstone-result-item">
					<div class="gemstone-result-label">需要一级宝石</div>
					<div class="gemstone-result-value">{{ getRequiredCount() }} 颗</div>
				</div>
				<div class="gemstone-result-item gemstone-result-total">
					<div class="gemstone-result-label">总需要金钱</div>
					<div class="gemstone-result-value">{{ calculatedPrice > 0 ? formatPrice(calculatedPrice) : '请输入单价'
					}}</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
// 结构
import {
	defineComponent,
	onMounted,
	ref,
	watch,
	reactive
} from 'vue';

// 模块化
export default defineComponent({
	name: 'Gemstone', // 组件名称
	props: {
		// 接收父组件数据

	},
	components: {
		// 定义子组件
	},
	// 主要是组件内交互事件
	setup(props, ctx) {
		// 变量声明 - 按在template中出现的顺序排列
		const gemTypes = ref([
			// 1类宝石：普通宝石，2个合成，10级后每级公式不同，最高20级
			{ id: 'normal', name: '普通宝石', type: 1, maxLevel: 20 },
			// 2类宝石：星辉石，3个合成，9级后每级公式不同，最高11级
			{ id: 'star', name: '星辉石', type: 2, maxLevel: 11 },
			// 3类宝石：五色灵尘	2+1合成，最高15级
			{ id: 'color', name: '五色灵尘', type: 3, maxLevel: 15 }
		]);

		const selectedGemType = ref('normal'); // 默认选中普通宝石
		const selectedLevel = ref(1); // 默认选择最小等级
		const basePrice = ref(0);
		const calculatedPrice = ref(0);

		// 计算属性 - 按在template中出现的顺序排列
		// 暂无计算属性

		// 监听器 - 按在template中出现的顺序排列
		watch(selectedLevel, handlePriceCalculate);
		watch(selectedGemType, handlePriceCalculate);

		// 交互方法 - 按在template中出现的顺序排列
		/**
		 * 处理宝石类型选择
		 * @param {string} gemId - 宝石类型ID
		 * @description 用户点击宝石类型时的响应方法
		 */
		const handleGemTypeSelect = (gemId) => {
			selectedGemType.value = gemId;
			// 切换宝石类型时，自动设置到最小等级
			selectedLevel.value = 1;
			handlePriceCalculate();
		};

		/**
		 * 处理等级选择
		 * @param {number} level - 选择的等级
		 * @description 用户点击等级按钮时的响应方法
		 */
		const handleLevelSelect = (level) => {
			selectedLevel.value = level;
			handlePriceCalculate();
		};

		/**
		 * 获取当前宝石类型的等级范围
		 * @returns {number[]} 等级数组
		 * @description 根据宝石类型获取其最大等级
		 */
		const getLevelRange = () => {
			const gem = gemTypes.value.find(g => g.id === selectedGemType.value);
			if (!gem) return [1]; // 默认返回最小等级

			const levels = [];
			for (let i = 1; i <= gem.maxLevel; i++) {
				levels.push(i);
			}
			return levels;
		};

		/**
		 * 计算1类宝石所需数量
		 * @param {number} level - 目标等级
		 * @returns {number} 所需一级宝石数量
		 * @description 1类宝石：2个合成，10级后每级公式不同
		 */
		const calculateType1Count = (level) => {
			// 验证等级范围
			if (level < 1 || level > 20) {
				return 0;
			}

			let result = 0;
			switch (level) {
				case 1:
				case 2:
				case 3:
				case 4:
				case 5:
				case 6:
				case 7:
				case 8:
				case 9:
				case 10:
				case 11:
					result = Math.pow(2, level - 1);
					break;
				case 12:
					result = 2 * calculateType1Count(11) +
						calculateType1Count(3) +
						calculateType1Count(5) +
						calculateType1Count(6);
					break;
				case 13:
					result = 2 * calculateType1Count(12) +
						calculateType1Count(9);
					break;
				case 14:
					result = 2 * calculateType1Count(13) +
						calculateType1Count(9) +
						calculateType1Count(10);
					break;
				case 15:
					result = 2 * calculateType1Count(14) +
						calculateType1Count(9) +
						calculateType1Count(12);
					break;
				case 16:
					result = 2 * calculateType1Count(15) +
						calculateType1Count(11) +
						calculateType1Count(12) +
						calculateType1Count(13);
					break;
				case 17:
					result = 2 * calculateType1Count(16) +
						calculateType1Count(15);
					break;
				case 18:
					result = 2 * calculateType1Count(17) +
						calculateType1Count(13) +
						calculateType1Count(14) +
						calculateType1Count(16);
					break;
				case 19:
					result = 2 * calculateType1Count(18) +
						calculateType1Count(15) +
						calculateType1Count(16) +
						calculateType1Count(17);
					break;
				case 20:
					result = 2 * calculateType1Count(19) +
						calculateType1Count(17) +
						2 * calculateType1Count(18);
					break;
				default:
					result = 0;
			}

			console.log(`1类宝石 ${level}级 计算结果: ${result}`);
			return result;
		};

		/**
		 * 计算2类宝石所需数量
		 * @param {number} level - 目标等级
		 * @returns {number} 所需一级宝石数量
		 * @description 2类宝石：3个合成，9级后每级公式不同
		 */
		const calculateType2Count = (level) => {
			// 验证等级范围
			if (level < 1 || level > 11) {
				return 0;
			}

			let result = 0;
			switch (level) {
				case 1:
				case 2:
				case 3:
				case 4:
				case 5:
				case 6:
				case 7:
				case 8:
					result = Math.pow(3, level - 1);
					break;
				case 9:
					result = 3 * calculateType2Count(8) +
						calculateType2Count(5);
					break;
				case 10:
					result = 3 * calculateType2Count(9) +
						calculateType2Count(6) +
						calculateType2Count(7);
					break;
				case 11:
					result = 3 * calculateType2Count(10) +
						calculateType2Count(9);
					break;
				default:
					result = 0;
			}

			console.log(`2类宝石 ${level}级 计算结果: ${result}`);
			return result;
		};

		/**
		 * 计算3类宝石所需数量
		 * @param {number} level - 目标等级
		 * @returns {number} 所需一级宝石数量
		 * @description 3类宝石：2个低一级 + 1个低二级，递归公式 count(n) = 2*count(n-1) + 1*count(n-2)
		 */
		const calculateType3Count = (level) => {
			// 验证等级范围
			if (level < 1 || level > 15) {
				return 0;
			}

			let result = 0;

			// 基础情况
			if (level === 1) {
				result = 1; // 1级需要1个1级宝石
			} else if (level === 2) {
				result = 2; // 2级需要2个1级宝石 (2*1 + 1*0 = 2)
			} else {
				// 递归公式：count(n) = 2*count(n-1) + 1*count(n-2)
				result = 2 * calculateType3Count(level - 1) + calculateType3Count(level - 2);
			}

			console.log(`3类宝石 ${level}级 计算结果: ${result}`);
			return result;
		};

		/**
		 * 处理价格输入
		 * @description 处理价格输入时的验证和计算
		 */
		const handlePriceInput = () => {
			// 验证价格范围
			let price = Number(basePrice.value);

			if (isNaN(price) || price < 0) {
				price = 0;
			} else if (price > 10000000) {
				price = 10000000;
			}

			// 更新价格值
			basePrice.value = price;

			// 触发价格计算
			handlePriceCalculate();
		};

		/**
		 * 处理价格输入框失焦
		 * @description 失焦时进行最终的价格验证
		 */
		const handlePriceBlur = () => {
			handlePriceInput();
		};

		/**
		 * 处理价格计算
		 * @description 根据选择的宝石类型、等级和单价计算总费用
		 */
		const handlePriceCalculate = () => {
			if (basePrice.value && selectedLevel.value && selectedGemType.value) {
				const gem = gemTypes.value.find(g => g.id === selectedGemType.value);
				if (gem) {
					let requiredCount = 0;

					// 根据宝石类型计算所需数量
					switch (gem.type) {
						case 1:
							requiredCount = calculateType1Count(selectedLevel.value);
							break;
						case 2:
							requiredCount = calculateType2Count(selectedLevel.value);
							break;
						case 3:
							requiredCount = calculateType3Count(selectedLevel.value);
							break;
						default:
							requiredCount = 0;
					}

					// 计算总价格：数量 × 单价
					calculatedPrice.value = requiredCount * Number(basePrice.value);

					// 添加调试信息
					console.log(`价格计算: ${gem.name} ${selectedLevel.value}级, 数量: ${requiredCount}, 单价: ${basePrice.value}, 总价: ${calculatedPrice.value}`);
				}
			}
		};

		/**
		 * 格式化价格显示
		 * @param {number} price - 价格数值
		 * @returns {string} 格式化后的价格字符串
		 * @description 将价格数值转换为亿/万单位的显示格式
		 */
		const formatPrice = (price) => {
			if (price >= 100000000) {
				// 大于等于1亿时，显示为"亿"单位
				const billion = Math.floor(price / 100000000);
				const million = Math.floor((price % 100000000) / 10000);
				return `${billion}亿${million}万`;
			} else if (price >= 10000) {
				// 大于等于1万时，显示为"万"单位，保留2位小数
				return (price / 10000).toFixed(2) + '万';
			} else {
				// 小于1万时，直接显示数值
				return price.toLocaleString();
			}
		};

		/**
		 * 获取所需宝石数量
		 * @returns {string} 格式化后的数量字符串
		 * @description 根据选择的宝石类型和等级计算所需数量
		 */
		const getRequiredCount = () => {
			if (!selectedGemType.value || !selectedLevel.value) return '0';

			const gem = gemTypes.value.find(g => g.id === selectedGemType.value);
			if (!gem) return '0';

			let count = 0;
			console.log(`开始计算: ${gem.name}, 类型: ${gem.type}, 等级: ${selectedLevel.value}`);

			switch (gem.type) {
				case 1:
					count = calculateType1Count(selectedLevel.value);
					console.log(`1类宝石计算: ${selectedLevel.value}级 = ${count}颗`);
					break;
				case 2:
					count = calculateType2Count(selectedLevel.value);
					console.log(`2类宝石计算: ${selectedLevel.value}级 = ${count}颗`);
					break;
				case 3:
					count = calculateType3Count(selectedLevel.value);
					console.log(`3类宝石计算: ${selectedLevel.value}级 = ${count}颗`);
					break;
				default:
					count = 0;
					console.log(`未知宝石类型: ${gem.type}`);
			}

			// 添加调试信息
			console.log(`最终结果: ${gem.name}, 等级: ${selectedLevel.value}, 计算数量: ${count}`);

			return count.toLocaleString();
		};

		/**
		 * 获取宝石类型信息
		 * @returns {string} 宝石类型描述
		 * @description 返回当前选择宝石的类型信息
		 */
		const getGemTypeInfo = () => {
			const gem = gemTypes.value.find(g => g.id === selectedGemType.value);
			if (!gem) return '未选择';

			const typeNames = {
				1: '普通宝石(12级开始额外材料)',
				2: '星辉石(9级开始额外材料)',
				3: '五色灵尘(3级开始低一级两颗+低二级一颗)'
			};

			return typeNames[gem.type] || '未知类型';
		};

		/**
		 * 获取最高等级
		 * @returns {string} 最高等级字符串
		 * @description 返回当前选择宝石的最高等级
		 */
		const getMaxLevel = () => {
			const gem = gemTypes.value.find(g => g.id === selectedGemType.value);
			return gem ? gem.maxLevel : 0;
		};

		/**
		 * 获取价格提示
		 * @returns {string} 格式化后的价格提示字符串
		 * @description 根据输入的价格值生成提示信息
		 */
		const getPriceHint = () => {
			if (!basePrice.value) return '';

			const price = Number(basePrice.value);
			if (price >= 100000000) {
				// 大于等于1亿时，显示为"亿"单位
				const billion = Math.floor(price / 100000000);
				const million = Math.floor((price % 100000000) / 10000);
				if (million > 0) {
					return `${billion}亿${million}万`;
				} else {
					return `${billion}亿`;
				}
			} else if (price >= 10000) {
				// 大于等于1万时，显示为"万"单位，保留2位小数
				return (price / 10000).toFixed(2) + '万';
			} else {
				// 小于1万时，直接显示数值
				return price.toLocaleString();
			}
		};

		onMounted(() => {
			// 初始化计算
			handlePriceCalculate();
		});

		return {
			gemTypes,
			selectedGemType,
			selectedLevel,
			basePrice,
			calculatedPrice,
			handleGemTypeSelect,
			handleLevelSelect,
			getLevelRange,
			handlePriceInput,
			handlePriceBlur,
			handlePriceCalculate,
			formatPrice,
			getRequiredCount,
			getGemTypeInfo,
			getMaxLevel,
			getPriceHint
		};
	},
	// 组件之间交互事件
	methods: {

	},
	// 生命周期 - 创建完成（访问DOM元素）
	beforeCreate() {

	},
	// 生命周期 - 创建完成（访问当前this实例）
	created() {

	},
	// 生命周期 - 挂载完成（访问当前this实例）
	mounted() {

	},
	// 生命周期 - 更新之前（访问当前this实例）
	beforeUpdate() {

	},
	// 生命周期 - 更新之前（访问当前this实例）
	updated() {

	},
	// 生命周期 - 销毁之前（访问当前this实例）
	unmounted() {

	},
	// 生命周期 - 组件激活（访问当前this实例）
	activated() {

	},
	// 生命周期 - 组件停用（访问当前this实例）
	deactivated() {

	},
	// 生命周期 - 子孙组件错误时
	errorCaptured() {

	}
});
</script>

<style lang='less' scoped>
@import '../../static/style/common.less';

/* scoped 使用得定义的样式只在本页面内生效  */
.gemstone-container {
	width: 100%;
	min-height: calc(~" 100vh - 32rpx ");
	background: @color-bg;
	padding: @page-padding;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;

	.gemstone-section {
		.card();
		.pageContent();
	}

	.gemstone-section-title {
		.sectionTitle();
	}
}

.gemstone-tab-list {
	display: flex;
	justify-content: space-between;
	margin-bottom: 16rpx;

	.gemstone-tab-item {
		flex: 1;
		margin: 0 6rpx;
		padding: 20rpx 16rpx;
		text-align: center;
		background: #f8f9fa;
		border: 1rpx solid @color-border;
		border-radius: 12rpx;
		cursor: pointer;
		transition: all 0.2s ease;
		font-size: 28rpx;
		font-weight: 500;
		color: @color-text-muted;

		&:first-child {
			margin-left: 0;
		}

		&:last-child {
			margin-right: 0;
		}

		&:hover {
			background: @color-hover-bg;
			border-color: @color-primary;
			color: @color-primary;
		}

		&.gemstone-tab-active {
			background: @color-primary;
			color: #fff;
			border-color: @color-primary;
		}

		.gemstone-tab-name {
			font-size: 28rpx;
			font-weight: 500;
		}
	}
}

.gemstone-level-buttons {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
	align-items: center;
	padding: 20rpx 0;

	.gemstone-level-btn {
		.btnBase();

		&:hover {
			.btnHover();
		}

		&.gemstone-level-btn-active {
			.btnActive();
		}

		.gemstone-level-btn-text {
			font-size: @btn-font;
			font-weight: 500;
			color: inherit;
		}
	}
}

.gemstone-input-group {
	display: flex;
	flex-direction: column;

	.gemstone-input-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 28rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.gemstone-input-label {
			color: @color-text;
			font-size: 28rpx;
			font-weight: 500;
			margin-bottom: 12rpx;
		}

		.gemstone-input-wrapper {
			display: flex;
			flex-direction: row;
			align-items: center;
			position: relative;
		}

		.gemstone-input-field {
			flex: 1;
			padding: 20rpx 24rpx;
			border: 1rpx solid @color-border;
			border-radius: 12rpx;
			font-size: 32rpx;
			outline: none;
			transition: all 0.2s ease;
			background: #fafafa;
			color: @color-text;

			&:focus {
				border-color: @color-primary;
				background: #fff;
				box-shadow: 0 0 0 3rpx rgba(52, 152, 219, 0.1);
			}

			&::placeholder {
				color: #bdc3c7;
			}
		}

		.gemstone-price-hint {
			margin-left: 16rpx;
			padding: 20rpx 24rpx;
			background: #e8f4fd;
			border: 1rpx solid #b3d9f2;
			border-radius: 8rpx;
			font-size: 32rpx;
			color: #2980b9;
			font-weight: 700;
			white-space: nowrap;
		}
	}
}

.gemstone-result-section {
	background: #f8f9fa;
	border-radius: 16rpx;
	border: 1rpx solid @color-border-strong;
}

.gemstone-result-list {
	display: flex;
	flex-direction: column;

	.gemstone-result-item {
		.resultItem();
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.gemstone-result-item:last-child {
		margin-bottom: 0;
	}

	.gemstone-result-total {
		background: @color-hover-bg;
		border-left: 4rpx solid @color-primary;
	}

	.gemstone-result-label {
		color: @color-label;
		font-size: 28rpx;
		font-weight: 500;
		min-width: 180rpx;
		max-width: 180rpx;
	}

	.gemstone-result-value {
		color: @color-text;
		font-size: 30rpx;
		font-weight: 600;
	}
}
</style>